<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%win}}".
 *
 * @property string $code
 * @property integer $prizeId
 * @property integer $createdAt
 * @property integer $isExchange
 * @property string $openid
 *
 * @property Prize $prize
 * @property User $user
 */
class Win extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%win}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['code', 'prizeId', 'createdAt', 'openid'], 'required'],
            [['prizeId', 'createdAt', 'isExchange'], 'integer'],
            [['code'], 'string', 'max' => 14],
            [['openid'], 'string', 'max' => 40],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'code' => 'Code',
            'prizeId' => '奖品ID',
            'createdAt' => '中将时间',
            'isExchange' => '是否领奖',
            'openid' => 'Openid',
        ];
    }

    public function beforeValidate()
    {
        if ($this->isNewRecord) {
            do {
                $this->code = date('ymdHi') . rand(1000, 9999);
                $isExists = static::find()->where(['code' => $this->code])->exists();
            } while ($isExists);
            $this->createdAt = time();
            $this->openid = Yii::$app->user->id;
        }
        return parent::beforeValidate();
    }

    public function getPrize()
    {
        return $this->hasOne(Prize::className(), ['prizeId' => 'prizeId']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['openid' => 'openid']);
    }
}
